package com.innovation.ic.cyz.admin.thread;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.cyz.base.pojo.constant.RabbitMqConstants;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.service.cyz.RepairOrderService;
import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @desc   监听虎趣->远大支持论坛的工单回复队列
 * @author linuo
 * @time   2022年11月21日13:45:42
 */
public class ListenHqToCyzRepairReplyQueueThread extends Thread {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private RepairOrderService repairOrderService;

    private Channel channel;

    /** erp交换机 */
    private String exchange;

    public ListenHqToCyzRepairReplyQueueThread(Channel channel, String exchange, RepairOrderService repairOrderService) {
        this.repairOrderService = repairOrderService;
        this.channel = channel;
        this.exchange = exchange;
    }

    @SneakyThrows
    @Override
    public void run() {
        String routingKey = RabbitMqConstants.HQ_CYZ_REPAIRORDER_REPLY_EXCHANGE;
        String queue = routingKey;
        channel.queueBind(queue, exchange, routingKey);
        channel.exchangeDeclare(exchange, RabbitMqConstants.DIRECT_TYPE, true);
        channel.queueDeclare(queue, true, false, false, null);
        Consumer callback = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
                String bodyString = new String(body);
                logger.info("接收到的队列:[{}]的消息为:[{}]", queue, bodyString);
                try {
                    JSONObject jsonObject = JSON.parseObject(bodyString);
                    if(jsonObject != null && !jsonObject.isEmpty()) {
                        ServiceResult<Boolean> serviceResult = repairOrderService.handleHqReplyRepairOrderMqMsg(jsonObject);
                        logger.info(serviceResult.getMessage());
                    }
                    logger.info("虎趣->远大支持论坛的工单回复队列处理结束");
                } catch (Exception e) {
                    logger.error("监听队列:[{}]时出现问题,原因:", queue, e);
                }
            }
        };
        channel.basicConsume(queue, true, callback);
    }
}